import {
	sha256
} from './js-sha256.js'
import moment from './moment.js'

/**
 * 密码加密
 * @param password
 */
function passwordEncry(password) {
	return sha256(password);
}

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function GMT08toLocal(time, format = 'YYYY-MM-DD HH:mm:ss') {
	if (!time) {
		return '';
	}
	let offset = moment().utcOffset()
	let local = moment(time).utc().utcOffset(offset).format(format)
	return local;
}

function LocalToGMT08(time, format = 'YYYY-MM-DD HH:mm:ss') {
	if (!time) {
		return '';
	}
	let gmt08 = moment(time).utc().utcOffset(480).format(format)
	return gmt08;
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

function datetimeFormat(date = new Date(), format) {
	format = format || 'YYYY-MM-DD HH:mm:ss';

	const fn = function(d) {
		return ('0' + d).slice(-2);
	};

	const d = new Date(date);
	const formats = {
		YYYY: d.getFullYear(),
		MM: fn(d.getMonth() + 1),
		DD: fn(d.getDate()),
		HH: fn(d.getHours()),
		mm: fn(d.getMinutes()),
		ss: fn(d.getSeconds())
	};

	return format.replace(/([a-z])\1+/ig, function(a) {
		return formats[a] || a;
	});
}

function getUrlParam(paramname, url) {
	var paramname = paramname.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
	var regexS = "[\\?&]" + paramname + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(url);
	var param_value = results === null ? '' : results[1];

	return param_value;
}

function toDuration(seconds) {
	console.log('lang',uni.getStorageSync('langStore'))
	// 两个时间戳相差的毫秒数
	var usedTime = seconds * 1000;
	// 计算相差的天数  
	var days = Math.floor(usedTime / (24 * 3600 * 1000));
	// 计算天数后剩余的毫秒数
	var leave1 = usedTime % (24 * 3600 * 1000);
	// 计算出小时数  
	var hours = Math.floor(leave1 / (3600 * 1000));
	// 计算小时数后剩余的毫秒数
	var leave2 = leave1 % (3600 * 1000);
	// 计算相差分钟数
	var minutes = Math.floor(leave2 / (60 * 1000));
	// 计算分钟数后剩余的毫秒数
	var leave3 = leave2 % (60 * 1000);
	// 计算分钟数后剩余的毫秒数
	var second = Math.floor(leave3 / 1000);
	var time = ''
	if (days != 0) {
		time += days + (uni.getStorageSync('langStore') == 0 ?"天":"days")
	}
	if (hours != 0) {
		time += hours + (uni.getStorageSync('langStore') == 0 ?"时":"h")
	}
	if (minutes != 0) {
		time += minutes + (uni.getStorageSync('langStore') == 0 ?"分":"min")
	}
	if (second != 0) {
		time += second + (uni.getStorageSync('langStore') == 0 ?"秒":"sec")
	}
	return time;
}

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	passwordEncry: passwordEncry,
	datetimeFormat: datetimeFormat,
	getUrlParam: getUrlParam,
	toDuration:toDuration,
	GMT08toLocal:GMT08toLocal,
	LocalToGMT08:LocalToGMT08
}
